//
// Created by 倪加奇 on 17-1-23.
// Email: drnijq@126.com
// Copyright (c) 2017 杭州威固网络科技有限公司. All rights reserved.
//

#include "tcp_echo_connetion.h"

#define ARR_LEN 128

tcp_echo_connetion::tcp_echo_connetion(boost::asio::io_service &io_service)
        : _socket(io_service), _arr_buf(new char[ARR_LEN]),
          _str_host("Un-know ip"), _ns_port(0) {
    memset(&_arr_buf[0], 0x0, ARR_LEN);
}

tcp_echo_connetion::pointer tcp_echo_connetion::create_pointer(boost::asio::io_service &io_service) {
    return tcp_echo_connetion::pointer(new tcp_echo_connetion(io_service));
}

tcp::socket &tcp_echo_connetion::socket() {
    return _socket;
}

void tcp_echo_connetion::start() {
    _socket.async_read_some(boost::asio::buffer(&_arr_buf[0], ARR_LEN),
                            boost::bind(&tcp_echo_connetion::handle_read, shared_from_this(),
                                        boost::asio::placeholders::bytes_transferred(),
                                        boost::asio::placeholders::error()));
}

void tcp_echo_connetion::handle_read(std::size_t data_len, const boost::system::error_code &error) {
    if (boost::system::errc::success != error) {
        print_log(error.message());
        return;
    }

    std::size_t last_data_position = data_len - 1;

    while ( ('\r' == _arr_buf[last_data_position]) || ('\n' == _arr_buf[last_data_position]) ) {
        --last_data_position;
    }

    std::string str_echo("Received data: ");
    str_echo.append(&_arr_buf[0], last_data_position + 1);
    print_log(str_echo);

    _socket.async_write_some(boost::asio::buffer(&_arr_buf[0], data_len),
                             boost::bind(&tcp_echo_connetion::handle_write,
                                         shared_from_this(),
                                         boost::asio::placeholders::error()));

    start();
}

void tcp_echo_connetion::print_log(const std::string &info) {
    std::cout << info << " (Connection info: HOST = " << _str_host
              << ", PORT = " << _ns_port << ")" << std::endl;
}

void tcp_echo_connetion::first_start() {
    _str_host = _socket.remote_endpoint().address().to_string();
    _ns_port = _socket.remote_endpoint().port();

    print_log("Connection started");
}

void tcp_echo_connetion::handle_write(const boost::system::error_code &error) {
    if (boost::system::errc::success != error) {
        print_log(error.message());
        return;
    }
}
